package cre.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.jdbc.core.namedparam.NamedParameterJdbcDaoSupport;
import org.springframework.jdbc.core.simple.ParameterizedRowMapper;

import cre.domain.Account;

public class AccountDao extends NamedParameterJdbcDaoSupport {
	
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public void saveAccount(Account account) {
		String sql = "insert into account(id,name,age,sex) " + "values(:id,:name,:age,:sex)";
		Map paramMap = new HashMap();
		paramMap.put("id", account.getId());
		paramMap.put("name", account.getName());
		paramMap.put("age", account.getAge());
		paramMap.put("sex", account.getSex());
		getNamedParameterJdbcTemplate().update(sql, paramMap);
	}

	@SuppressWarnings({ "unchecked", "rawtypes" })
	public Account getAccountById(int id) {
		String sql = "select id,name,age,sex from account where id=:id";
		Map paramMap = new HashMap();
		paramMap.put("id", id);
		List<Account> matches = getNamedParameterJdbcTemplate().query(sql, paramMap,
				new ParameterizedRowMapper<Account>() {
					@Override
					public Account mapRow(ResultSet rs, int rowNum) throws SQLException {
						Account a = new Account();
						a.setId(rs.getInt(1));
						a.setName(rs.getString(2));
						a.setAge(rs.getInt(3));
						a.setSex(rs.getString(4));
						return a;
					}

				});
		return matches.size() > 0 ? matches.get(0) : null;
	}

	@SuppressWarnings({ "unchecked", "rawtypes" })
	public void removeAccount(int id) {
		String sql = "delete from account where id=:id";
		Map paramMap = new HashMap();
		paramMap.put("id", id);
		getNamedParameterJdbcTemplate().update(sql, paramMap);
	}

}